﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Data.Sqlite;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using System.Net.Http;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// 初始化 TODO 表
void InitTodoDb()
{
    using var conn = new SqliteConnection("Data Source=todo.db;"); conn.Open();
    var cmd = conn.CreateCommand();
    cmd.CommandText = @"
CREATE TABLE IF NOT EXISTS TodoItem(Id INTEGER PRIMARY KEY, Title TEXT, Completed INTEGER);
";
    cmd.ExecuteNonQuery();
}
InitTodoDb();

app.MapGet("/todos", () => {
    var list = new List<object>();
    using var conn = new SqliteConnection("Data Source=todo.db;"); conn.Open();
    var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM TodoItem";
    using var rdr = cmd.ExecuteReader();
    while (rdr.Read()) list.Add(new { Id = rdr.GetInt32(0), Title = rdr.GetString(1), Completed = rdr.GetInt32(2) == 1 });
    return Results.Ok(list);
});

app.MapPost("/todos", async (HttpContext hc) => {
    var todo = await hc.Request.ReadFromJsonAsync<Todo>();
    using var conn = new SqliteConnection("Data Source=todo.db;"); conn.Open();
    var cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO TodoItem(Title,Completed) VALUES(@t,0)";
    cmd.Parameters.AddWithValue("@t", todo.Title);
    cmd.ExecuteNonQuery();
    return Results.Created($"/todos/{todo.Title}", todo);
});

app.MapPut("/todos/{id:int}", async (int id, HttpContext hc) => {
    var todo = await hc.Request.ReadFromJsonAsync<Todo>();
    using var conn = new SqliteConnection("Data Source=todo.db;"); conn.Open();
    var cmd = conn.CreateCommand(); cmd.CommandText = "UPDATE TodoItem SET Title=@t,Completed=@c WHERE Id=@id";
    cmd.Parameters.AddWithValue("@t", todo.Title);
    cmd.Parameters.AddWithValue("@c", todo.Completed ? 1 : 0);
    cmd.Parameters.AddWithValue("@id", id);
    cmd.ExecuteNonQuery();
    return Results.NoContent();
});

app.MapDelete("/todos/{id:int}", (int id) => {
    using var conn = new SqliteConnection("Data Source=todo.db;"); conn.Open();
    var cmd = conn.CreateCommand(); cmd.CommandText = "DELETE FROM TodoItem WHERE Id=@id";
    cmd.Parameters.AddWithValue("@id", id);
    cmd.ExecuteNonQuery();
    return Results.NoContent();
});

app.Run();
